package com.ccp.dev.qbdms.util;

import org.apache.tika.Tika;
import org.apache.tika.exception.TikaException;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.parser.AutoDetectParser;
import org.apache.tika.parser.ParseContext;
import org.apache.tika.parser.Parser;
import org.apache.tika.sax.BodyContentHandler;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static java.util.regex.Pattern.*;

public class TikaUtils {


    /**
     * 根据Tika得到文档的内容，这种比下面那种获取的要简单很多，
     * 据tika的文档上说，效率没有下面的那种高，可能封装的比较多
     * @param f
     * @return
     * @throws IOException
     * @throws TikaException
     */
    public static String tikaTool(File f) throws IOException, TikaException {
        Tika tika = new Tika();
        Metadata metadata = new Metadata();
        metadata.set(Metadata.AUTHOR, "空号");//重新设置文档的媒体内容
        metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
        String str = tika.parseToString(new FileInputStream(f),metadata);
        for(String name:metadata.names()) {
            System.out.println(name+":"+metadata.get(name));
        }
        return str;
    }

    /**
     * 根据Parser得到文档的内容
     * @param f
     * @return
     */
    public static String fileToTxt(File f) {
        Parser parser = new AutoDetectParser();//自动检测文档类型，自动创建相应的解析器
        InputStream is = null;
        try {
            Metadata metadata = new Metadata();
            metadata.set(Metadata.AUTHOR, "空号");//重新设置文档的媒体内容
            metadata.set(Metadata.RESOURCE_NAME_KEY, f.getName());
            is = new FileInputStream(f);
            ContentHandler handler = new BodyContentHandler();
            ParseContext context = new ParseContext();
            context.set(Parser.class,parser);
            parser.parse(is,handler, metadata,context);
            for(String name:metadata.names()) {
                System.out.println(name+":"+metadata.get(name));
            }
            return handler.toString();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        } catch (TikaException e) {
            e.printStackTrace();
        } finally {
            try {
                if(is!=null) {
                    is.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }


    public  static  String fileToString(String  path)  {
        Tika tika = new Tika();
        // -1应该是不做限制 默认 10W
        tika.setMaxStringLength(-1);
//         path="E:\\304\\200.doc";
        try {
            String text = tika.parseToString(new File(path));
            tika.getMaxStringLength();
            return  text;
        }catch (Exception e){
            e.printStackTrace();
        }
        return "";
    }

    public static String replaceBlank(String str) {
        String dest = "";
        if (str!=null) {
//            横向跳格|回车|换行|空格 "\t|\r|\n| "
            Pattern p = compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }
    public static void main(String[] args) throws Exception {

        // Create a Tika instance with the default configuration
        Tika tika = new Tika();
        // -1应该是不做限制 默认 10W
        tika.setMaxStringLength(-1);
        String path="C:\\Users\\Administrator\\Desktop\\质量大数据\\通用上报英文记录内容（2016-03-01）.xls";
        String text = tika.parseToString(new File(path));
        tika.getMaxStringLength();
        // Parse all given files and print out the extracted text content
        System.err.println(text);
        System.err.println( tika.getMaxStringLength());
    }

}
